package com.example.xcService.pojo.tool;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class KGTool {
    public static String generateSign(Map<String, String> params, String secret)
    {
        TreeMap<String, String> map = new TreeMap<String, String>();
        Iterator<String> itParam = params.keySet().iterator();
        while (itParam.hasNext())
        {
            String name = itParam.next();
            map.put(name, params.get(name));
        }
        String signStr = "";
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext())
        {
            String name = it.next();
            String value = map.get(name);
            signStr = signStr + name + "=" + value + "&";
        }
        signStr = signStr.substring(0, signStr.length() - 1);
        return generateMacSignature(secret, signStr);
    }
    public static String generateMacSignature(String secret, String data)
    {
        byte[] byteHMAC = null;
        try
        {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKey secretKey = new SecretKeySpec(secret.getBytes("utf-8"),
                    "HmacSHA1");
            mac.init(secretKey);
            byteHMAC = mac.doFinal(data.getBytes("utf-8"));
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (InvalidKeyException e)
        {
            e.printStackTrace();
        }
        catch (IllegalStateException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        String result = byte2hex(byteHMAC);
        return result;
    }
    //二行制转字符串
    public static String byte2hex(byte[] b)
    {
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; b != null && n < b.length; n++)
        {
            stmp = Integer.toHexString(b[n] & 0XFF);
            if (stmp.length() == 1)
                hs.append('0');
            hs.append(stmp);
        }
        return hs.toString().toUpperCase();
    }
}
